#include "os_semaphore.h"
#include <stdio.h>



int os_semaphore_init(os_semaphore_st * const semaphore, uint16_t init_value,uint16_t max_count)
{
    if(NULL == semaphore)
    {
        return -2; // Invalid semaphore pointer
    }
    semaphore->count = init_value; // Initialize semaphore count
    semaphore->max_count = max_count; // Set maximum count
    return 0; // Success
}
int os_semaphore_give(os_semaphore_st * const semaphore)
{
    if(NULL == semaphore)
    {
        return -2; // Invalid semaphore pointer
    }

    os_enter_critical();
    if (semaphore->count < semaphore->max_count) // Check if semaphore can be given
    {
        semaphore->count++; // Increment semaphore count
        os_exit_critical();
        return 0; // Success
    }
    os_exit_critical();
    return -1; // Semaphore already at maximum count
}

int os_semaphore_try_take(os_semaphore_st * const semaphore)
{
    if(NULL == semaphore)
    {
        return -2; // Invalid semaphore pointer
    }

    if (semaphore->count > 0) // Check if semaphore can be taken
    {
        os_enter_critical();
        semaphore->count--; // Decrement semaphore count
        os_exit_critical();
        return 0; // Success
    }

    return -1; // Semaphore already at zero count
}
